<template>
  <!-- 主内容区域 -->
  <div class="content-area">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon fee-type">
              <el-icon><Collection /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.totalCount }}</div>
              <div class="stat-label">费用类型</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon active">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.activeCount }}</div>
              <div class="stat-label">启用项目</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon inactive">
              <el-icon><Close /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.inactiveCount }}</div>
              <div class="stat-label">停用项目</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon updated">
              <el-icon><Refresh /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.todayUpdateCount }}</div>
              <div class="stat-label">今日更新</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选卡片 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">费用名称</div>
          <el-input
            v-model="filters.item_name"
            placeholder="请输入费用名称"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">费用类型</div>
          <el-select
            v-model="filters.category_id"
            placeholder="请选择费用类型"
            clearable
          >
            <el-option
              v-for="cate in fee_category_options"
              :key="cate.value"
              :label="cate.label"
              :value="cate.value"
            ></el-option>
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">状态</div>
          <el-select
            v-model="filters.is_active"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </div>
        <div class="filter-item">
          <div class="filter-label">科室</div>
          <el-select
            v-model="filters.department_ids"
            placeholder="请选择科室"
            clearable
            filterable
          >
            <el-option
              v-for="dept in department_options"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </div>
      </div>
      <div class="action-buttons">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" @click="searchFees">查询</el-button>
        <el-button type="success" @click="showCreateFeeDialog">
          <el-icon><Plus /></el-icon>
          新增费用
        </el-button>
        <el-button type="warning" @click="exportFeeTemplate">
          <el-icon><Download /></el-icon>
          导出模板
        </el-button>
        <el-button type="info" @click="showImportDialog">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
      </div>
    </div>

    <!-- 费用配置表格 -->
    <div class="fee-table">
      <div class="table-header">
        <div class="table-title">费用配置列表</div>
        <div class="table-tools">
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 新增：可横向滚动的表格容器，超出宽度时只在此处出现横向滚动 -->
      <div class="table-scroll">
        <el-table class="fee-config-table" :data="fee_configs" stripe>
          <el-table-column type="selection" width="55" />
          <el-table-column prop="item_code" label="费用编码" width="120" />
          <el-table-column prop="item_name" label="费用名称" min-width="220" />
          <el-table-column label="费用类型" width="120">
            <template #default="{ row }">
              <el-tag :type="get_category_tag(row.category_id)" size="small">
                {{ format_fee_category(row.category_id) }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- 新增：检查类型列 -->
          <el-table-column
            label="检查类型"
            width="120"
            v-if="showCheckTypeColumn"
          >
            <template #default="{ row }">
              <span>{{ format_check_type(row.check_type) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="标准价格" width="120">
            <template #default="{ row }">
              <span class="amount"
                >¥{{ format_amount(row.standard_price) }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="医保价格" width="120">
            <template #default="{ row }">
              ¥{{ format_amount(row.insurance_price) }}
            </template>
          </el-table-column>
          <el-table-column label="成本价格" width="120">
            <template #default="{ row }">
              ¥{{ format_amount(row.cost_price) }}
            </template>
          </el-table-column>          
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-switch
                v-model="row.is_active"
                :active-value="1"
                :inactive-value="0"
                @change="handle_status_change(row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="update_time" label="更新时间" width="180" />
          <el-table-column label="操作" width="300" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons-cell">
                <el-button size="small" @click="viewFeeDetails(row)"
                  >详情</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="editFeeConfig(row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  @click="deleteFeeConfig(row)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current_page"
          v-model:page-size="pagination.page_size"
          :page-sizes="[10, 20, 50, 100]"
          :page-count="pagination.pageTotal"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 费用配置对话框 -->
  <el-dialog
    v-model="fee_dialog.visible"
    :title="fee_dialog.is_edit ? '编辑费用配置' : '新增费用配置'"
    width="800px"
  >
    <el-form
      :model="item_form"
      label-width="100px"
      :rules="item_rules"
      ref="item_form_ref"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="费用编码" prop="item_code">
            <el-input
              v-model="item_form.item_code"
              placeholder="自动生成或手动输入"
              :disabled="fee_dialog.is_edit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="费用名称" prop="item_name">
            <el-input
              v-model="item_form.item_name"
              placeholder="请输入费用名称"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="费用类型" prop="category_id">
            <el-select
              v-model="item_form.category_id"
              placeholder="请选择费用类型"
              @change="handle_category_change"
            >
              <el-option
                v-for="cate in fee_category_options"
                :key="cate.value"
                :label="cate.label"
                :value="cate.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="适用科室" prop="department_ids">
            <el-select
              v-model="item_form.department_ids"
              placeholder="请选择适用科室"
              filterable
              multiple
              collapse-tags
            >
              <el-option
                v-for="dept in department_options"
                :key="dept.value"
                :label="dept.label"
                :value="dept.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 新增：检查类型选择，仅当费用类型为检查费时显示 -->
      <el-row :gutter="20" v-if="showCheckTypeField">
        <el-col :span="12">
          <el-form-item label="检查类型" prop="check_type">
            <el-select
              v-model="item_form.check_type"
              placeholder="请选择检查类型"
              clearable
            >
              <el-option label="检验检查" value="lab" />
              <el-option label="影像检查" value="imaging" />
              <el-option label="功能检查" value="functional" />
              <el-option label="内镜检查" value="endoscopy" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 新增：执行部门选择，仅当费用类型为检查费时显示 -->
      <el-row :gutter="20" v-if="showCheckTypeField">
        <el-col :span="12">
          <el-form-item label="执行科室" prop="operation_department_id">
            <el-select
              v-model="item_form.operation_department_id"
              placeholder="请选择执行科室"
              clearable
              @change="handleOperationDepartmentChange"
            >
              <el-option
                v-for="dept in department_options"
                :key="dept.value"
                :label="dept.label"
                :value="dept.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="标准价格" prop="standard_price">
            <el-input-number
              v-model="item_form.standard_price"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="医保价格" prop="insurance_price">
            <el-input-number
              v-model="item_form.insurance_price"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="成本价格" prop="cost_price">
            <el-input-number
              v-model="item_form.cost_price"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="计价单位" prop="unit">
            <el-input v-model="item_form.unit" placeholder="如：次、项、盒等" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="医保类别" prop="insurance_type">
            <el-select
              v-model="item_form.insurance_type"
              placeholder="请选择医保类别"
            >
              <el-option label="甲类" value="A" />
              <el-option label="乙类" value="B" />
              <el-option label="丙类" value="C" />
              <el-option label="自费" value="self" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="费用说明" prop="description">
        <el-input
          v-model="item_form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入费用详细说明"
        />
      </el-form-item>

      <el-form-item label="状态" prop="is_active">
        <el-radio-group v-model="item_form.is_active">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="fee_dialog.visible = false">取消</el-button>
      <el-button type="primary" @click="submit_item_form">确认</el-button>
    </template>
  </el-dialog>

  <!-- 费用详情抽屉 -->
  <el-drawer
    v-model="detail_drawer.visible"
    title="费用详情"
    :direction="'rtl'"
    size="40%"
  >
    <div class="fee-detail" v-if="current_item">
      <div class="detail-header">
        <h3>{{ current_item.item_name }}</h3>
        <el-tag :type="current_item.is_active === 1 ? 'success' : 'info'">
          {{ current_item.is_active === 1 ? "启用" : "停用" }}
        </el-tag>
      </div>

      <el-divider />

      <div class="detail-section">
        <h4>基本信息</h4>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="费用编码">{{
            current_item.item_code
          }}</el-descriptions-item>
          <el-descriptions-item label="费用类型">{{
            format_fee_category(current_item.category_id)
          }}</el-descriptions-item>
          <!-- 新增：检查类型详情 -->
          <el-descriptions-item label="检查类型" v-if="current_item.check_type">
            {{ format_check_type(current_item.check_type) }}
          </el-descriptions-item>
          <el-descriptions-item label="执行科室">
            {{ current_item.operation_department_name }}
          </el-descriptions-item>
          <el-descriptions-item label="适用科室">{{
            current_item.department_names
          }}</el-descriptions-item>
          <el-descriptions-item label="计价单位">{{
            current_item.unit
          }}</el-descriptions-item>
          <el-descriptions-item label="医保类别">{{
            format_insurance_type(current_item.insurance_type)
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="detail-section">
        <h4>价格信息</h4>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="标准价格"
            >¥{{
              format_amount(current_item.standard_price)
            }}</el-descriptions-item
          >
          <el-descriptions-item label="医保价格"
            >¥{{
              format_amount(current_item.insurance_price)
            }}</el-descriptions-item
          >
          <el-descriptions-item label="成本价格"
            >¥{{ format_amount(current_item.cost_price) }}</el-descriptions-item
          >
        </el-descriptions>
      </div>

      <div class="detail-section" v-if="current_item.description">
        <h4>费用说明</h4>
        <p>{{ current_item.description }}</p>
      </div>

      <div class="detail-section">
        <h4>操作记录</h4>
        <el-timeline>
          <el-timeline-item
            v-for="record in current_item.operation_records"
            :key="record.id"
            :timestamp="record.time"
          >
            {{ record.action }} - {{ record.operator }}
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>
  </el-drawer>

  <!-- 批量导入对话框 -->
  <el-dialog
    v-model="import_dialog.visible"
    title="批量导入费用配置"
    width="500px"
  >
    <el-upload
      class="upload-demo"
      drag
      action="#"
      :auto-upload="false"
      :on-change="handleFileChange"
      accept=".xlsx,.xls"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">只能上传 xlsx/xls 文件，且不超过10MB</div>
      </template>
    </el-upload>

    <div class="import-template">
      <el-button type="text" @click="downloadTemplate">下载导入模板</el-button>
    </div>

    <template #footer>
      <el-button @click="import_dialog.visible = false">取消</el-button>
      <el-button type="primary" @click="handleImport">开始导入</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 引入后端API接口（示例）
import {
  getDepartmentList,
  getFeeCateList,
  addFeeItem,
  editFeeItem,
  getFeeItemPagerDataBySearch,
  statsFeeItemCount,
} from "@/api/api";

const filters = reactive({
  item_name: "",
  category_id: "",
  is_active: "",
  department_ids: "",
});

const stats = reactive({
  totalCount: 0,
  activeCount: 0,
  inactiveCount: 0,
  todayUpdateCount: 0,
});

const pagination = reactive({
  current_page: 1,
  page_size: 10,
  total: 0,
  pageTotal: 0,
});

// 科室选项
const department_options = ref([]);
// 费用类型选项
const fee_category_options = ref([]);

// 费用配置数据（数组，字段与表保持一致）
const fee_configs = ref([]);

// 对话框控制
const fee_dialog = reactive({
  visible: false,
  is_edit: false,
});

// 表单模型（使用与 h_fee_item_tb 一致的字段名）
const item_form = reactive({
  item_id: null,
  item_code: "",
  item_name: "",
  category_id: "",
  operation_department_id: "", //执行科室ID
  operation_department_name: "", //执行科室名称
  department_ids: [], // 前端使用数组，提交时转为逗号字符串
  standard_price: 0,
  insurance_price: 0,
  cost_price: 0,
  unit: "次",
  insurance_type: "B",
  description: "",
  is_active: 1,
  check_type: "", // 新增：检查类型字段
});

const item_rules = {
  item_code: [{ required: true, message: "请输入费用编码", trigger: "blur" }],
  item_name: [{ required: true, message: "请输入费用名称", trigger: "blur" }],
  category_id: [
    { required: true, message: "请选择费用类型", trigger: "change" },
  ],
  standard_price: [
    { required: true, message: "请输入标准价格", trigger: "blur" },
  ],
  unit: [{ required: true, message: "请输入计价单位", trigger: "blur" }],
  operation_department_id: [
    { 
      validator: (rule, value, callback) => {
        // 只有当费用类型为检查费时才验证
        const isCheckFee = fee_category_options.value.some(
          cate => cate.value === item_form.category_id && cate.label.includes('检查')
        );
        if (isCheckFee && !value) {
          callback(new Error('检查费必须选择执行科室'));
        } else {
          callback();
        }
      },
      trigger: 'change' 
    }
  ],
};

const item_form_ref = ref(null);

const detail_drawer = reactive({
  visible: false,
});

const current_item = ref(null);

const import_dialog = reactive({
  visible: false,
});

// 计算属性：是否显示检查类型字段（仅当费用类型为检查费时）
const showCheckTypeField = computed(() => {
  // 假设检查费的category_id为某个特定值，这里需要根据实际情况调整
  // 如果费用类型选项中有检查费，可以根据label判断，或者根据value判断
  const isCheckFee = fee_category_options.value.some(
    (cate) =>
      cate.value === item_form.category_id && cate.label.includes("检查")
  );
  return isCheckFee;
});

// 计算属性：是否在表格中显示检查类型列
const showCheckTypeColumn = computed(() => {
  return fee_configs.value.some((item) => item.check_type);
});

const resetFilters = () => {
  filters.item_name = "";
  filters.category_id = "";
  filters.is_active = "";
  filters.department_ids = "";
  load_fee_configs();
};

const searchFees = () => {
  pagination.current_page = 1;
  load_fee_configs();
};

// 加载统计数据
const load_stats = async () => {
  try {
    const response = await statsFeeItemCount();
    console.log("统计数据:", response);
    if (response.code == 200) {
      if (response.data) {
        stats.totalCount = response.data.totalCount || 0;
        stats.activeCount = response.data.activeCount || 0;
        stats.inactiveCount = response.data.inactiveCount || 0;
        stats.todayUpdateCount = response.data.todayUpdateCount || 0;
      }
    } else {
      ElMessage.error(response.message || "获取统计数据失败");
    }
  } catch (error) {
    console.error("加载统计数据失败:", error);
  }
};

// 加载科室列表
const load_departments_list = async () => {
  try {
    const response = await getDepartmentList();
    department_options.value = response.data.map((dept) => ({
      label: dept.department_name,
      value: dept.department_id,
    }));
    // TODO: 调用后端接口 getDepartmentList() 并赋值 department_options
  } catch (error) {
    console.error("加载科室列表失败:", error);
  }
};

// 加载费用类型列表（value 使用 category_id）
const load_fee_cate_list = async () => {
  try {
    const response = await getFeeCateList();
    fee_category_options.value = response.data.map((cate) => ({
      label: cate.category_name,
      value: cate.category_id,
    }));
    // TODO: 调用后端接口 getFeeCateList() 并赋值 fee_category_options
  } catch (error) {
    console.error("加载费用类型列表失败:", error);
  }
};

const load_fee_configs = async () => {
  // TODO: 推荐使用后端分页接口 getFeeItemPagerDataBySearch(filters, pagination) 获取数据
  // 示例（伪代码）：
  let mockData = [];

  const payload = {
    item_name: filters.item_name,
    category_id: filters.category_id,
    is_active: filters.is_active,
    department_ids: filters.department_ids, // 根据后端接口名调整
    currentPage: pagination.current_page,
    pageSize: pagination.page_size,
  };
  const res = await getFeeItemPagerDataBySearch(payload);
  console.log("费用配置数据:", res);
  if (res.code == 200) {
    mockData = res.data.data;
    pagination.total = res.data.total || 0;
    pagination.pageTotal = res.data.pageTotal || 0;
  } else {
    ElMessage.error(res.message || "获取费用配置失败");
    return;
  }

  let filteredData = mockData;

  if (filters.item_name) {
    filteredData = filteredData.filter(
      (item) => item.item_name && item.item_name.includes(filters.item_name)
    );
  }

  if (filters.category_id) {
    filteredData = filteredData.filter(
      (item) => item.category_id === filters.category_id
    );
  }

  if (
    filters.is_active !== "" &&
    filters.is_active !== null &&
    filters.is_active !== undefined
  ) {
    filteredData = filteredData.filter(
      (item) => item.is_active === filters.is_active
    );
  }

  if (filters.department_ids) {
    filteredData = filteredData.filter((item) => {
      if (!item.department_ids) return false;
      const deptIds = String(item.department_ids)
        .split(",")
        .map((x) => String(x));
      return deptIds.includes(String(filters.department_ids));
    });
  }

  fee_configs.value = filteredData;
  pagination.total = filteredData.length;
};

const handleSizeChange = (size) => {
  pagination.page_size = size;
  load_fee_configs();
};

const handleCurrentChange = (page) => {
  pagination.current_page = page;
  load_fee_configs();
};

const showCreateFeeDialog = () => {
  Object.assign(item_form, {
    item_id: null,
    item_code: `FEE${Date.now().toString().slice(-6)}`,
    item_name: "",
    category_id: "",
    // 新增：执行部门字段
    operation_department_id: "",
    operation_department_name: "",
    department_ids: [],
    standard_price: 0,
    insurance_price: 0,
    cost_price: 0,
    unit: "次",
    insurance_type: "B",
    description: "",
    is_active: 1,
    check_type: "", // 新增：检查类型字段
  });
  fee_dialog.is_edit = false;
  fee_dialog.visible = true;
};

const editFeeConfig = (row) => {
  Object.assign(item_form, {
    item_id: row.item_id || null,
    item_code: row.item_code,
    item_name: row.item_name,
    category_id: row.category_id,
    // 新增：执行部门字段
    operation_department_id: row.operation_department_id || "",
    operation_department_name: row.operation_department_name || "",
    department_ids: Array.isArray(row.department_ids)
      ? row.department_ids
      : row.department_ids
      ? String(row.department_ids).split(",")
      : [],
    standard_price: row.standard_price || 0,
    insurance_price: row.insurance_price || 0,
    cost_price: row.cost_price || 0,
    unit: row.unit || "次",
    insurance_type: row.insurance_type || "B",
    description: row.description || "",
    is_active: typeof row.is_active !== "undefined" ? row.is_active : 1,
    check_type: row.check_type || "", // 新增：检查类型字段
  });
  fee_dialog.is_edit = true;
  fee_dialog.visible = true;
};

const viewFeeDetails = (row) => {
  current_item.value = row;
  detail_drawer.visible = true;
};

const deleteFeeConfig = (row) => {
  ElMessageBox.confirm(`确定要删除费用项目"${row.item_name}"吗？`, "删除确认", {
    confirmButtonText: "确定删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // TODO: 在此调用后端删除接口，例如 await deleteFeeItem({ item_id: row.item_id });
      ElMessage.success("删除成功");
      load_fee_configs();
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handle_status_change = (row) => {
  const action = row.is_active === 1 ? "启用" : "停用";
  // TODO: 在此调用后端接口更新 is_active，例如 await editFeeItem({ item_id: row.item_id, is_active: row.is_active });
  ElMessage.success(`已${action}费用项目"${row.item_name}"`);
};

const handle_category_change = (categoryId) => {
  // 若后端返回类别名称并需要根据类别设置单位，可在此扩展逻辑
  item_form.unit = item_form.unit || "次";

  // 如果切换费用类型为非检查费，清空检查类型
  const isCheckFee = fee_category_options.value.some(
    (cate) => cate.value === categoryId && cate.label.includes("检查")
  );
  if (!isCheckFee) {
    item_form.check_type = "";
    item_form.operation_department_id = "";
    item_form.operation_department_name = "";
  }
};

//添加执行部门变更处理方法
const handleOperationDepartmentChange = (departmentId) => {
  const selectedDept = department_options.value.find(
    (dept) => dept.value === departmentId
  );
  if (selectedDept) {
    item_form.operation_department_name = selectedDept.label;
  } else {
    item_form.operation_department_name = "";
  }
};

const submit_item_form = async () => {
  try {
    await item_form_ref.value.validate();

    const payload = {
      // 直接使用与表对应的字段名
      item_id: item_form.item_id,
      item_code: item_form.item_code,
      item_name: item_form.item_name,
      category_id: item_form.category_id,
      // 新增：执行部门字段
      operation_department_id: item_form.operation_department_id,
      operation_department_name: item_form.operation_department_name,
      department_ids: Array.isArray(item_form.department_ids)
        ? item_form.department_ids.join(",")
        : item_form.department_ids || "",
      standard_price: item_form.standard_price,
      insurance_price: item_form.insurance_price,
      cost_price: item_form.cost_price,
      unit: item_form.unit,
      insurance_type: item_form.insurance_type,
      description: item_form.description,
      is_active: item_form.is_active,
      check_type: item_form.check_type, // 新增：检查类型字段
    };

    if (fee_dialog.is_edit) {
      // TODO: 调用后端编辑接口，例如： await editFeeItem(payload);
      const res = await editFeeItem(payload);
      if (res.code == 200) {
        ElMessage.success("费用配置更新成功");
        load_stats();
      } else {
        ElMessage.error(res.message || "费用配置更新失败");
        return;
      }
    } else {
      // TODO: 调用后端新增接口，例如： await addFeeItem(payload);
      const res = await addFeeItem(payload);
      if (res.code == 200) {
        ElMessage.success("费用配置新增成功");
        load_stats();
      } else {
        ElMessage.error(res.message || "费用配置新增失败");
        return;
      }
    }

    fee_dialog.visible = false;
    load_fee_configs();
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

const showImportDialog = () => {
  import_dialog.visible = true;
};

const handleFileChange = (file) => {
  console.log("文件选择:", file);
};

const handleImport = () => {
  // TODO: 解析上传文件并调用后端批量导入接口；示例： await importFeeItems(formData)
  ElMessage.success("批量导入成功");
  import_dialog.visible = false;
  load_fee_configs();
};

const downloadTemplate = () => {
  ElMessage.info("开始下载导入模板");
};

const exportFeeTemplate = () => {
  // TODO: 调用后端导出接口并触发文件下载
  ElMessage.success("费用模板导出成功");
};

const refreshData = () => {
  load_fee_configs();
  ElMessage.success("数据已刷新");
};

const format_amount = (amount) => {
  return Number(amount || 0).toFixed(2);
};

const format_fee_category = (category_id) => {
  const found = fee_category_options.value.find((c) => c.value === category_id);
  return found ? found.label : category_id || "";
};

// 新增：格式化检查类型显示
const format_check_type = (type) => {
  const typeMap = {
    lab: "检验检查",
    imaging: "影像检查",
    functional: "功能检查",
    endoscopy: "内镜检查",
  };
  return typeMap[type] || type || "";
};

const format_insurance_type = (type) => {
  const typeMap = {
    A: "甲类",
    B: "乙类",
    C: "丙类",
    self: "自费",
  };
  return typeMap[type] || type;
};

const get_category_tag = (category_id) => {
  const found = fee_category_options.value.find((c) => c.value === category_id);
  if (!found) return "info";
  const name = found.label || "";
  if (name.includes("药") || name.includes("药品")) return "danger";
  if (name.includes("手术")) return "error";
  if (name.includes("住院")) return "warning";
  if (name.includes("挂号")) return "success";
  return "info";
};

onMounted(() => {
  load_stats();
  load_departments_list();
  load_fee_cate_list();
  load_fee_configs();
});
</script>

<style lang="scss" scoped>
.content-area {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  height: 0; // 添加这行
  min-height: 100%; // 添加这行
  overflow-y: auto; // 确保有这行
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    font-size: 24px;
    color: white;

    &.fee-type {
      background: linear-gradient(135deg, #409eff, #79bbff);
    }
    &.active {
      background: linear-gradient(135deg, #67c23a, #85ce61);
    }
    &.inactive {
      background: linear-gradient(135deg, #909399, #a6a9ad);
    }
    &.updated {
      background: linear-gradient(135deg, #e6a23c, #ebb563);
    }
  }

  .stat-content {
    flex: 1;

    .stat-value {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 4px;
    }

    .stat-label {
      font-size: 14px;
      color: #909399;
    }
  }
}

.filter-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
  flex: 1;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 16px;
}

.fee-table {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
}

.table-tools {
  display: flex;
  gap: 12px;
}

.amount {
  font-weight: bold;
  color: #f56c6c;
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.fee-detail {
  padding: 20px;

  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .detail-section {
    margin-bottom: 24px;

    h4 {
      margin: 0 0 12px 0;
      color: #303133;
      font-size: 16px;
    }
  }
}

.import-template {
  margin-top: 16px;
  text-align: center;
}

/* 新增：表格横向滚动容器，确保超出部分只在表格内部滚动 */
.table-scroll {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  /* 给滚动条一点内边距，避免贴边 */
  padding-bottom: 6px;
}

/* 给内部表格设置最小宽度，超过容器宽度时触发横向滚动 */
.fee-config-table {
  min-width: 1100px; /* 根据列数和最小列宽调整该值 */
  width: max-content;
}

/* 确保表头和表体内部也受最小宽度约束，避免列错位（scoped 下使用 :deep 穿透） */
:deep(.fee-config-table .el-table__header) {
  min-width: 1100px;
}

:deep(.fee-config-table .el-table__body) {
  min-width: 1100px;
}
</style>